package com.oldking.controller;

import com.oldking.domain.AudioInfo;
import com.oldking.domain.VideoData;
import com.oldking.domain.VideoInfo;
import com.oldking.domain.VideoTask;
import com.oldking.utils.*;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import start.StarterClass;

import java.io.*;
import java.net.URL;
import java.util.*;

@Component
public class MediaManageController implements Initializable {

    private static String durationTime = VideoData.getVideoInfoByKey(VideoData.getKey()).getDuration();

    private MediaPlayer mediaPlayer;
    private StarterClass application;

    @FXML
    private MediaView mediaAudioView;
    @FXML
    private GridPane gridPaneId;
    @FXML
    private TableView videoManageView;
    @FXML
    private TableView audioManageView;
    @FXML
    private Slider volSlider;
    @FXML
    private Slider minSlider;
    @FXML
    private TextFlow currentTime;
    @FXML
    private TextFlow totalTime;


    @FXML
    private TableColumn taskName;
    @FXML
    private TableColumn startTime;
    @FXML
    private TableColumn audioName;
    @FXML
    private TableColumn progress;
    @FXML
    private TableColumn endTime;
    @FXML
    private TableColumn opration;
    @FXML
    private TableColumn taskVideoPath;

    @FXML
    private TableColumn audioTaskNameColumn;
    @FXML
    private TableColumn audioSpdColumn;
    @FXML
    private TableColumn audioSizeColumn;
    @FXML
    private TableColumn audioPitColumn;
    @FXML
    private TableColumn audioVolColumn;
    @FXML
    private TableColumn audioPerColumn;
    @FXML
    private TableColumn pathColumn;
    @FXML
    private TableColumn audioOpration;
    @FXML
    private Pane sliderPane;

    @FXML
    private void back_videotask(ActionEvent event) {
        mediaPlayer.stop();
        application.gotoeditvideo("item");
    }

    @FXML
    private void openvidFile(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4");
        fileChooser.getExtensionFilters().add(filter);
        File file = fileChooser.showOpenDialog(null);

    }

    public void setApp(StarterClass application) {
        this.application = application;
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        initPage();
    }

    private void initPage() {
        File file = new File(VideoData.getKey());
        String filePath = file.toURI().toString();
        if (filePath != null) {
            Media media = new Media(filePath);
            mediaPlayer = new MediaPlayer(media);
            mediaAudioView.setMediaPlayer(mediaPlayer);

            Text tt = new Text(" / " + durationTime);
            tt.setFont(new Font(15));
            totalTime.getChildren().add(tt);
            volSlider.setValue(mediaPlayer.getVolume() * 100);
            volSlider.valueProperty().addListener(new InvalidationListener() {
                @Override
                public void invalidated(Observable observable) {
                    mediaPlayer.setVolume(volSlider.getValue() / 100);
                }
            });
            Text current = new Text();
            int t = CommonTimeUtil.Stringtime2Second(durationTime);
            minSlider.setMax(t);

            mediaPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
                @Override
                public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
                    minSlider.setValue(newValue.toSeconds());
                    VideoData.setCurrentTime((int) minSlider.getValue());
                    long l = Math.round(minSlider.getValue());
                    setCurrentByTime(l, current);

                }
            });
            addSliderMouseDragged(current);

            minSlider.setOnMouseMoved(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (!"HAND".equals(Cursor.HAND)) {
                        minSlider.setCursor(Cursor.HAND);
                    }
                }
            });

            sliderPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    mediaPlayer.pause();
                    // create LineTo
                    LineTo Lineto = new LineTo(event.getScreenX(), event.getScreenY());
                    // create moveto
                    MoveTo moveto = new MoveTo(300, 300);
                    // create a Path
                    Path path = new Path(moveto, Lineto);

                    // set fill for path
                    path.setFill(Color.BLACK);

                    // set stroke width
                    path.setStrokeWidth(2);
                    sliderPane.getChildren().add(path);

                    long l = Math.round(minSlider.getValue());
                    try {
                        mediaPlayer.seek(Duration.seconds(minSlider.getValue()));
                        VideoData.setCurrentTime((int) minSlider.getValue());
                        setCurrentByTime(l, current);
                    } catch (Exception e) {

                    }
                }
            });

            List<AudioInfo> aList = VideoData.getAudioInfoList();
            HBox hBox = new HBox();
            HBox composeBox = new HBox();
            if (aList.size() > 0) {
                ChoiceBox cb = getChoiceBox(getAudioList(filePath, aList));
                hBox.getChildren().addAll(cb);
                Button composeButton = getComposeButton();
                composeBox.getChildren().addAll(composeButton);
            }

            VideoInfo videoInfo = VideoData.getVideoInfoByKey(VideoData.getKey());
            ObservableList<VideoTask> taskList = FXCollections.observableArrayList();
            if (videoInfo.getVideotask().size() > 0 && hBox.getChildren().size() > 0) {
                for (int i = 0; i < videoInfo.getVideotask().size(); i++) {
                    //   hBox.getChildren().get(0).setId("choicBox" + (i + 1));
                    HBox hBoxCopy = new HBox();
                    HBox composeBoxCopy = new HBox();

                    ChoiceBox cb = showSelectedChoiceBox(aList, videoInfo, i);

                    hBoxCopy.getChildren().addAll(cb);
                    Button composeButton = getComposeButton();
                    composeButton.setId(String.valueOf(i + 1));
                    composeBoxCopy.getChildren().addAll(composeButton);
                    hBoxCopy.getChildren().get(0).setId("choicBox" + (i + 1));

                    videoInfo.getVideotask().get(i).setAudioName(hBoxCopy);
                    videoInfo.getVideotask().get(i).setOpration(composeBoxCopy);
                }
            }
            initAudioTableColumn();
            initVideoTableColumn();
            taskList.addAll(videoInfo.getVideotask());
            videoManageView.setItems(taskList);
            videoManageView.setEditable(true);
            showAllRectlage(minSlider);

            ObservableList<AudioInfo> audioInfoList = getAudioList(filePath, aList);
            if (audioInfoList.size() == 0) {
                return;
            }
            audioManageView.setItems(audioInfoList);

        }
    }

    private ObservableList<AudioInfo> getAudioList(String filePath, List<AudioInfo> aList) {
        String substring = filePath.substring(6, filePath.length());
        String parent = new File(substring.substring(0, substring.lastIndexOf("."))).getPath();
        ObservableList<AudioInfo> items = FXCollections.observableArrayList();
        for (AudioInfo ai : aList) {
            String audioParent = new File(ai.getPathColumn()).getParent();
            if (parent.equals(audioParent)) {
                items.add(ai);
            }
        }
        return items;
    }

    private ChoiceBox showSelectedChoiceBox(List<AudioInfo> aList, VideoInfo videoInfo, int i) {
        ChoiceBox cb = getChoiceBox(aList);

        if (videoInfo.getVideotask().get(i).getAudioName() != null) {
            ObservableList<Node> children = videoInfo.getVideotask().get(i).getAudioName().getChildren();
            for (int j = 0; j < children.size(); j++) {
                ChoiceBox choiceBox = (ChoiceBox) children.get(j);
                int selectedIndex = choiceBox.getSelectionModel().getSelectedIndex();
                cb.getSelectionModel().select(selectedIndex);
                break;

            }
        }
        return cb;
    }


    private Button getComposeButton() {
        Button composeButton = new Button("生成片段");
        composeButton.setId(String.valueOf(videoManageView.getItems().size() + 1));

        composeButton.setOnMouseClicked(ActionEvent -> {
            String id = ((Node) ActionEvent.getSource()).getId();
            VideoInfo info = VideoData.getVideoInfoByKey(VideoData.getKey());
            VideoTask videoTask = info.getVideotask().get(Integer.valueOf(id) - 1);
            ChoiceBox node = (ChoiceBox) videoTask.getAudioName().getChildren().get(0);
            if (videoTask.getTaskVideoPath() != null) {
                Button button = (Button) videoTask.getOpration().getChildren().get(0);
                button.setDisable(true);
                AlertMessageUtil.msg(Alert.AlertType.WARNING, "WARNING", "已经生成", "暂不可再次生成");
                return;
            }

            boolean flag = true;
            // videoTask的name下面创一个目录
            String mp3Path = "";
            String startTime = "";
            String endTime = "";
            String outFilePath = "/" + UUIDUtil.getUUID() + ".mp4";
            String outNewFilePath = "";
            String subtitlePath = "";
            if (node.getValue() == null) {
                flag = false;
                String path = info.getPath();
                outFilePath =  path.substring(0,path.lastIndexOf(".")) + "/" + videoTask.getTaskName() + ".mp4";
            } else {
                mp3Path = getAuditoPathById(info.getFileName(), node.getValue().toString());
                subtitlePath = mp3Path.replace(".mp3", ".srt");
                String parent = new File(mp3Path).getParent();
                outFilePath = parent + outFilePath;
                outNewFilePath = parent + "/" + videoTask.getTaskName() + ".mp4";

            }
            startTime = videoTask.getStartTime().getText();
            endTime = videoTask.getEndTime().getText();
            // 生成文件
            // processmp4 是表示不要原音 flag, 视频路径 path, 输出视频路径 outFilePath, mp3路径 mp3Path, 字幕路径 subtitlePath, 开始时间 startTime, 结束时间 endTime
            String originVideopath = info.getPath();

            // flag为true去音频
            String tempPath = FFmpegUtil.composeVideo(flag, originVideopath, outFilePath, startTime, endTime);
            if (!"".equals(tempPath) && flag) {
                // 生成音频和字幕
                String resultPath = FFmpegUtil.setVideomp3Andsrt(tempPath, mp3Path, subtitlePath, outNewFilePath);
                // 添加到视频文件列表
                setFilePathIntoText(resultPath);
                // 添加到字幕文件列表
                setSRTText2File(resultPath, subtitlePath);

                deleteTempFile(resultPath, tempPath);
                // 将视频路径放入表格
                setVideoTaskPath(flag, resultPath, id);
                mediaPlayer.stop();
                application.gotoaudiomanage("");
            }else {
                // 添加到视频文件列表
                setFilePathIntoText(outFilePath);
                // 将视频路径放入表格
                setVideoTaskPath(flag, outFilePath, id);
                mediaPlayer.stop();
                application.gotoaudiomanage("");
            }
            AlertMessageUtil.msg(Alert.AlertType.INFORMATION, "info", "视频片段已经生成", "");
        });
        return composeButton;
    }

    private void setSRTText2File(String resultPath, String subtitlePath) {
        File resultmp4File = new File(resultPath);
        String srtListFile = resultmp4File.getParent() + "/srtFile.srt";
        write2srtFile(srtListFile, resultPath, subtitlePath);

    }

    private void write2srtFile(String srtListFile, String resultPath, String subtitlePath) {
        // 不存在就将当前字幕文件的内容复制进去
        File filesrtListFile = new File(srtListFile);
        try {
            if (!filesrtListFile.exists()) {
                filesrtListFile.createNewFile();
                CommonFileUtil.copySrt2SrtListFile(filesrtListFile, subtitlePath);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取文件倒数第二行
        String last2LineValue = getFileLastLine(srtListFile, 2);
        String num = getFileLastLine(srtListFile, 3).replace("\t", "");
        List<String> values = getFileValueList(subtitlePath);
        String lastTime = last2LineValue.split("-->")[1].split(",")[0].trim();
        setSrtValue(Integer.valueOf(num.trim()) + 1, filesrtListFile, CommonTimeUtil.Stringtime2Second(lastTime), subtitlePath, values);

    }

    private List<String> getFileValueList(String srtListFile) {
        List<String> values = new ArrayList<>(0);
        FileReader fileReader = null;
        LineNumberReader reader = null;
        try {
            File file = new File(srtListFile);//文件路径
            fileReader = new FileReader(file);
            reader = new LineNumberReader(fileReader);

            String txt = "";
            int lines = 0;

            while (true) {
                lines++;
                txt = reader.readLine();
                if (lines % 3 == 0) {
                    values.add(txt);
                }
                if (txt == null) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                fileReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return values;
    }

    private String setSrtValue(int num, File filesrtListFile, int stringtime2Second, String subtitlePath, List<String> values) {
        String sub = getFileLastLine(subtitlePath, 2).trim().split("-->")[1].split(",")[0];
        int subNum = CommonTimeUtil.Stringtime2Second(sub);
        String result = "";
        InputStream is = null;
        try {
            is = new FileInputStream(subtitlePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
            int count = 0;

            for (int i = 1; i < subNum; i++) {
                String line = reader.readLine();
                if (line == null) {
                    return line;
                }
                PrintWriter pw = new PrintWriter(new FileWriter(filesrtListFile, true));
                line = line.trim();
                if ((i - 1) % 3 == 0) {
                    pw.println(num++);
                }
                if ((i - 2) % 3 == 0) {
                    String[] timeList = line.split("-->");
                    String start = timeList[0].split(",")[0];
                    String end = timeList[1].split(",")[0];
                    int startInt = CommonTimeUtil.Stringtime2Second(start) + stringtime2Second;
                    int endInt = CommonTimeUtil.Stringtime2Second(end) + stringtime2Second;
                    String lastStart = CommonTimeUtil.secondToTime((long) startInt);
                    String lastEnd = CommonTimeUtil.secondToTime((long) endInt);
                    pw.println(lastStart + ",0 --> " + lastEnd + ",0");
                }
                if (i % 3 == 0) {
                    pw.println(values.get(count));
                    count++;
                }
                pw.close();
            }
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }

    private void setFilePathIntoText(String resultPath) {
        File resultmp4File = new File(resultPath);
        String fileListPath = resultmp4File.getParent() + "/fileList.txt";
        File fileListFile = new File(fileListPath);
        try {
            if (!fileListFile.exists()) {
                fileListFile.createNewFile();
            }
            write2File(fileListFile, resultPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void write2File(File file, String mp4Path) {
        try {
            PrintWriter pw = new PrintWriter(new FileWriter(file, true));
            pw.println("file \'" + mp4Path + "\'");
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取文件内倒数第二行
    public static String getFileLastLine(String filePath, int num) {
        String lastLine = "";
        try {
            File file = new File(filePath);//文件路径
            FileReader fileReader = new FileReader(file);
            LineNumberReader reader = new LineNumberReader(fileReader);
            int lineNumber = (int) CommonFileUtil.getLineNumber(file);
            String txt = "";
            int lines = 0;
            while (true) {
                lines++;
                txt = reader.readLine();
                if (lines == (lineNumber - num - 1)) {
                    lastLine = reader.readLine();
                    break;
                }
            }
            reader.close();
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lastLine;
    }

    private void setVideoTaskPath(boolean flag, String resultPath, String id) {
        ObservableList<VideoTask> items = videoManageView.getItems();
        ObservableList<VideoTask> taskList = FXCollections.observableArrayList();
        items.get(Integer.valueOf(id) - 1).setTaskVideoPath(resultPath);
        if(flag){
            items.get(Integer.valueOf(id) - 1).setProgress("完成");
        }else {
            items.get(Integer.valueOf(id) - 1).setProgress("完毕");
        }

        taskList.addAll(items);
        VideoData.getVideoInfoByKey(VideoData.getKey()).setVideotask(taskList);
        videoManageView.setItems(taskList);
        videoManageView.setEditable(true);
    }

    private ChoiceBox getChoiceBox(List<AudioInfo> aList) {
        ChoiceBox cb = new ChoiceBox();
        //设置选择监听
        cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                if (oldValue.intValue() == -1) {
                    return;
                }
                AudioInfo a = (AudioInfo) audioManageView.getItems().get((newValue.intValue()));
                // String id = a.getId();
                TableRow tableRow = (TableRow) cb.getParent().getParent().getParent();
                tableRow.setItem(a);
                List<AudioInfo> audioInfoList = VideoData.getAudioInfoList();
            }
        });

        ObservableList<String> audioNameList = FXCollections.observableArrayList();
        for (int i = 0; i < aList.size(); i++) {
            audioNameList.add(aList.get(i).getAudioTaskNameColumn());
        }

        cb.setItems(audioNameList);
        return cb;
    }

    private void deleteTempFile(String resultPath, String tempPath) {
        if (!"".equals(resultPath)) {
            File f = new File(tempPath);
            if (f.exists()) {
                f.delete();
            }
        }
    }

    private String getAuditoPathById(String fileName, String audioId) {
        String substring = fileName.substring(0, fileName.lastIndexOf("."));
        AudioInfo audio = VideoData.getAudioInfoByKey(audioId);
        return audio.getPathColumn();
    }

    private void showAudioTable() {

    }

    private void showAllRectlage(Slider minSlider) {
        ObservableList<VideoTask> taskList = FXCollections.observableArrayList();
        List<VideoInfo> videoInfoList = VideoData.getVideoInfoList();
        for (VideoInfo videoInfo : videoInfoList) {
            List<VideoTask> videotask = videoInfo.getVideotask();
            taskList.addAll(videotask);
        }
        for (int i = 0; i < taskList.size(); i++) {
            VideoTask videoTask = taskList.get(i);
            int intStart = CommonTimeUtil.Stringtime2Second(videoTask.getStartTime().getText());
            int intEnd = CommonTimeUtil.Stringtime2Second(videoTask.getEndTime().getText());
            int t = CommonTimeUtil.Stringtime2Second(durationTime);
            double vStart = (intStart * this.minSlider.getPrefWidth() / t);
            double vEnd = (intEnd * this.minSlider.getPrefWidth() / t);
            String id = String.valueOf(i + 1);
            addOneSliderRectangle(sliderPane, "startTimeBtn", id, vStart);
            addOneSliderRectangle(sliderPane, "endTimeBtn", id, vEnd);
        }
    }


    private void addOneSliderRectangle(Pane sliderPane, String btnTypleText, String id, double v) {

        Rectangle rectangleStart = createSliderNewRectangle(CommonColorUtil.getColorByKey(Integer.valueOf(id)), v, btnTypleText + id, id);
        ObservableList<Node> children = sliderPane.getChildren();
        if (children.size() == 1) {
            sliderPane.getChildren().add(rectangleStart);
            return;
        }
        boolean flag = false;
        for (int i = 1; i < children.size(); i++) {
            if (ObjectUtils.isEmpty(children.get(i).getId())) {
                continue;
            }
            if (children.get(i).getId().contains(btnTypleText + id)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            for (int i = 1; i < children.size(); i++) {
                if (ObjectUtils.isEmpty(children.get(i).getId())) {
                    continue;
                }
                Rectangle r = (Rectangle) children.get(i);

                if (r.getId().equals(btnTypleText + id)) {
                    sliderPane.getChildren().set(i, rectangleStart);
                    return;
                }
            }
        } else {
            sliderPane.getChildren().add(rectangleStart);
        }
    }

    private void addSliderMouseDragged(Text current) {
        minSlider.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                long l = Math.round(minSlider.getValue());
                try {
                    mediaPlayer.seek(Duration.seconds(minSlider.getValue()));
                    VideoData.setCurrentTime((int) minSlider.getValue());
                    setCurrentByTime(l, current);
                } catch (Exception e) {

                }
            }
        });
    }

    private void setCurrentByTime(long l, Text current) {
        current.setFont(new Font(15));
        current.setText(CommonTimeUtil.secondToTime(l));
        if (currentTime.getChildren().size() == 0) {
            currentTime.getChildren().add(current);
        } else {
            currentTime.getChildren().set(0, current);
        }
    }

    @FXML
    private void playVid(ActionEvent event) {
        mediaPlayer.play();
        mediaPlayer.setRate(1);
    }

    @FXML
    private void pauseVid(ActionEvent event) {
        mediaPlayer.pause();
    }

    @FXML
    private void stopVid(ActionEvent event) {
        mediaPlayer.stop();
    }

    @FXML
    private void exitProg(ActionEvent event) {
        System.exit(0);
    }

    public void addVideoTask(ActionEvent actionEvent) {
        sliderPane.setStyle("-fx-background-color: #ffffff");
        addVideotask();
    }

    private void addVideotask() {
        ObservableList<VideoTask> items = videoManageView.getItems();
        ObservableList<VideoTask> taskList = FXCollections.observableArrayList();
        VideoInfo videoInfo = VideoData.getVideoInfoByKey(VideoData.getKey());
        if (checkIfTimeUpdated(videoInfo)) {
            AlertMessageUtil.msg(Alert.AlertType.WARNING, "warning", "未设置完成,不能新增", "开始或者结束时间未设置完成");
            return;
        }

        VideoTask videoTask = new VideoTask();
        videoTask.setId(UUIDUtil.getUUID());
        videoTask.setParentId(videoInfo.getId());
        videoTask.setTaskName(videoInfo.getFileName() + (items.size() + 1));

        taskList.add(videoTask);
        initVideoTableColumn();
        items.addAll(taskList);
        videoManageView.setItems(items);
        videoManageView.setEditable(true);
        taskName.setCellFactory(TextFieldTableCell.forTableColumn());
        videoInfo.getVideotask().add(videoTask);

    }

    private boolean checkIfTimeUpdated(VideoInfo videoInfo) {
        List<VideoTask> videotaskList = videoInfo.getVideotask();
        for (VideoTask videoTask : videotaskList) {
            String StartText = videoTask.getStartTime().getText();
            String endText = videoTask.getEndTime().getText();
            if ("设置".equals(StartText) || "设置".equals(endText)) {
                return true;
            }
        }
        return false;
    }


    private Rectangle createSliderNewRectangle(String color, double X, String nodeId, String id) {
        Rectangle rectangle = new Rectangle();
        rectangle.setId(nodeId);
        rectangle.setFill(Paint.valueOf(color));
        rectangle.setX(X);
        rectangle.setWidth(2.0);
        rectangle.setHeight(23.0);
        return rectangle;
    }

    private void initVideoTableColumn() {
        taskName.setCellValueFactory(new PropertyValueFactory("taskName"));
        startTime.setCellValueFactory(new PropertyValueFactory("startTime"));
        endTime.setCellValueFactory(new PropertyValueFactory("endTime"));
        taskVideoPath.setCellValueFactory(new PropertyValueFactory("taskVideoPath"));
        audioName.setCellValueFactory(new PropertyValueFactory("audioName"));
        progress.setCellValueFactory(new PropertyValueFactory("progress"));
        opration.setCellValueFactory(new PropertyValueFactory("opration"));
    }

    private void initAudioTableColumn() {
        audioTaskNameColumn.setCellValueFactory(new PropertyValueFactory("audioTaskNameColumn"));
        audioSizeColumn.setCellValueFactory(new PropertyValueFactory("audioSizeColumn"));
        audioPerColumn.setCellValueFactory(new PropertyValueFactory("audioPerColumn"));
        pathColumn.setCellValueFactory(new PropertyValueFactory("pathColumn"));
        audioOpration.setCellValueFactory(new PropertyValueFactory("audioOpration"));

    }

    public void delVideoTask(ActionEvent actionEvent) {
        ObservableList<VideoTask> videoTaskList = videoManageView.getItems();
        if (videoTaskList.size() == 0) {
            return;
        }
        VideoTask task = videoTaskList.get(videoTaskList.size() - 1);
        videoTaskList.remove(task);
        videoManageView.setItems(videoTaskList);
        String id = String.valueOf(videoTaskList.size() + 1);
        deleteOneAudio();
        sliderPane.setStyle("-fx-background-color: #ffffff");
    }

    public void deleteOneAudio() {
        File file = new File(VideoData.getKey());
        String filePath = file.toURI().toString();
        List<AudioInfo> aList = VideoData.getAudioInfoList();
        if (aList.size() == 0){
            AlertMessageUtil.msg(Alert.AlertType.WARNING, "warning", "列表已清空", "");
            return;
        }

        ObservableList<AudioInfo> audioInfoList = getDeleteAudioList(filePath, aList);
        audioManageView.setItems(audioInfoList);
    }

    private ObservableList<AudioInfo> getDeleteAudioList(String filePath, List<AudioInfo> aList) {
        ObservableList<AudioInfo> deleteAudioList = getAudioList(filePath, aList);
        aList.remove(deleteAudioList.get(deleteAudioList.size() - 1));
        deleteAudioList.remove(deleteAudioList.size() - 1);

        return deleteAudioList;
    }

    public void submitVideoTask(ActionEvent actionEvent) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                mergeVideos();
            }
        }).start();
    }

    private void mergeVideos() {
        VideoInfo videoInfo = VideoData.getVideoInfoByKey(VideoData.getKey());

        File file = new File(videoInfo.getPath());
        String output = file.getParent() + "/temp.mp4";
        String videoLastPath = file.getParent() + "/" + UUIDUtil.getUUID() + ".mp4";

        String taskVideoPath = videoInfo.getVideotask().get(0).getTaskVideoPath();
        File taskVideoFile = new File(taskVideoPath);
        File parentFile = taskVideoFile.getParentFile();
        String srtPath = taskVideoFile.getParent() + "/srtFile.srt";
        String fileListPath = taskVideoFile.getParent() + "\\fileList.txt";
        FFmpegUtil.mergeVideos(fileListPath, output);
        FFmpegUtil.setVideoSubtitles(output, videoLastPath, srtPath);
        try {
            Thread.sleep(20000);
        } catch (Exception e) {

        }
        File lastFile = new File(videoLastPath);
        if (lastFile.exists()) {
            new File(output).delete();
            // 删除生成的文件夹目录
            // CommonFileUtil.deleteDirectory(parentFile);
        }
    }


    public void addAudio(ActionEvent actionEvent) {
        mediaPlayer.stop();
        application.gotoaddaudio("item");
    }

    public void delAudio(ActionEvent actionEvent) {
    }
}